﻿
#include "RamDB.h"
#include "DBKey.h"
#include "Macro.h"
#include "DBKey.h"

RamDB::RamDB(QObject *parent)
: QObject(parent)
, mFileDB(QSettings::IniFormat, QSettings::UserScope,"DJI", "DJI Flight Simulator")
{
	Load();
}

RamDB::~RamDB()
{}

QString RamDB::Get(const KEY & key, const QString& defVal) const
{
	return mRamDB.value(key.name,defVal).toString();
}

void RamDB::Set(const KEY & key, const QString & value)
{
	QVariant var(value);
	mRamDB.insert(key.name, var);
	Save(key, var);
}

bool RamDB::GetBool(const KEY & key, bool defVal) const
{
	return mRamDB.value(key.name, defVal).toBool();
}

void RamDB::Set(const KEY & key, bool value)
{
	QVariant var(value);
	mRamDB.insert(key.name, var);
	Save(key, var);
}

int RamDB::GetInt(const KEY & key,int defVal) const
{
	return mRamDB.value(key.name,defVal).toInt();
}

void RamDB::Set(const KEY & key, int value)
{
	QVariant var(value);
	mRamDB.insert(key.name,var);
	Save(key, var);
}

void RamDB::Set(const KEY& key,const QJsonArray& val)
{
	QVariant var(val);
	mRamDB.insert(key.name,var);
	Save(key, var);
}

QJsonArray RamDB::GetJsonArray(const KEY& key,QJsonArray defVal) const
{
	return mRamDB.value(key.name,defVal).toJsonArray();
}

void RamDB::SetVariant(const KEY& key,const QVariant& var){
	mRamDB.insert(key.name,var);
	Save(key, var);
}

QVariant RamDB::GetVariant(const KEY& key,const QVariant& defVal) const{
	return mRamDB.value(key.name,defVal);
}

void RamDB::Load()
{
	QStringList keys = mFileDB.allKeys();
	for (const QString& key : keys) {
		FAIL_CONTINUE(DBKey::CheckNeedSave(key));
		mRamDB.insert(key, mFileDB.value(key));
	}
}

void RamDB::Save(const KEY & key, const QVariant & value)
{
	Q_EMIT DbSaved(key,value);
	FAIL_RET_VOID(key.save);
	mFileDB.setValue(key.name, value);
}

